package com.citytechinc.cmis.client.service
{
	import com.citytechinc.cmis.client.model.Document;
	import com.citytechinc.cmis.util.FileBuffer;
	
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	
	public class ContentStreamService
	{
		private var auth:String;
		
		private var documents:Array;
		
		public function ContentStreamService(auth:String, documents:Array)
		{
			this.auth = auth;
			this.documents = documents;
		}
		
		public function getContentStreams():Array 
		{
			var files:Array = new Array();
			
			for (var i:int = 0; i < documents.length; i++) 
			{
				var document:Document = Document(documents[i]);
				
				var file:File = File.createTempDirectory().resolvePath(document.fileName);
				
				var buffer:FileBuffer = new FileBuffer(file);
				
				var request:URLRequest = new URLRequest(document.url);
				
				var header:URLRequestHeader = new URLRequestHeader("Authorization", "Basic " + auth);
				
				request.requestHeaders.push(header);
				
				var loader:URLLoader = new URLLoader();
				
				loader.dataFormat = URLLoaderDataFormat.BINARY;
				loader.addEventListener(Event.COMPLETE, buffer.write);
				loader.load(request);
				
				files.push(file);
			}
			
			return files;

		}

	}
	
}